/**
 * File: Contigidfile2CoverageController.java
 * Created by: mhaimel
 * Created on: Jun 25, 2011
 * CVS:  $Id: Contigidfile2CoverageController.java 1.0 Jun 25, 2011 7:22:18 AM mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.graph;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import uk.ac.ebi.curtain.controller.SingleSubmitController;
import uk.ac.ebi.curtain.model.graph.curtain.ContigInfo;
import uk.ac.ebi.curtain.model.graph.curtain.CurtainGraph;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;
import uk.ac.ebi.velvet.model.Supercontig;

/**
 * @author mhaimel
 *
 */
public class Contigidfile2CoverageController extends SingleSubmitController<File, Serializable> {

	@Override
	protected void singleSubmit(List<File> inputList) {
		for(File dir : inputList){
			processDirectory(dir);
		}
	}

	private void processDirectory(File dir) {
		File nodeIdFile = Supercontig.getNodeIdOutputFile(dir);
		Collection<Long> nodeIDs = loadIds(nodeIdFile);
		long len = 0;
		long cov = 0;
		long rlen = 0;
		Set<Integer> cats = getContext().getArguments().getCategories();
		CurtainGraph g = getContext().getGraph();
		for(Long n : nodeIDs){
			ContigInfo v = g.getNode(n).getValue();
			len += v.getLength();
			for(Integer c : cats){
				if(rlen == 0){
					rlen = Double.valueOf(v.getAvgReadLength(c)).longValue(); // TODO ok for the moment
				}
				cov += v.getCoverageBpCount(c);
			}
		}
		try {
			FileUtils.writeStringToFile(new File(dir,"stats.txt"), cov+"\t"+len+"\t"+rlen);
		} catch (IOException e) {
			throw new CurtainUncheckedException(e);
		}
	}

	private Collection<Long> loadIds(File contigIdFile) {
		List<Long> contigIds = new LinkedList<Long>();
		BufferedReader in = null;
		try {
			in = new FileIO(contigIdFile).getBufferedReader();
			String line = null;
			while((line = in.readLine()) != null){
				line = line.trim();
				if(StringUtils.isNotBlank(line)){
					contigIds.add(Long.valueOf(line));
				}
			}
		} catch (IOException e) {
			throw new CurtainUncheckedException("Problems reading file " + contigIdFile,e);
		}finally{
			FileIO.closeQuietly(in);
		}
		return contigIds;
	}

	
}
